﻿using System;
using System.Collections.Generic;
using System.Web.Mvc;
using LuKou.Member.Domains;
using LuKou.Shopspace.Domains;
using LuKou.Web.BLL;
using LuKou.Web.BLL.Service;
using LuKou.Web.Controllers.Base;
using LuKou.Web.Core;
using LuKou.Web.Form;
using LuKou.Web.Helper;
using LuKou.Member.Services;
using LuKou.Member;
using LuKou.Web.UserAuth;
using LuKou.Shopspace;

namespace LuKou.Web.Controllers.Website
{
    /// <summary>
    /// 用户登录注册控制器
    /// </summary>
    public class AccountController : WebBaseController
    {
        #region 用户登录处理

        /// <summary>
        /// 用户登录页面
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult Login()
        {
            return View("login");
        }

        /// <summary>
        /// 用户登录数据处理
        /// </summary>
        /// <param name="user">用户登录信息</param>
        /// <param name="referrerUrl">登录来源地址</param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Login(LoginForm user, string referrerUrl)
        {
            if (!ModelState.IsValid
                || null == Session["VerifyCode"]
                || string.Compare(user.ValidateCode, Session["VerifyCode"].ToString(), StringComparison.CurrentCultureIgnoreCase) != 0)
            {
                if (!string.IsNullOrEmpty(user.ValidateCode))
                {
                    ModelState.AddModelError("ValidateCode", "请输入正确的验证码。");
                }
                return View("login");
            }

            //用户登录
            UserSession session = null;
            try
            {
                session = ServiceHelper.Get<IUserSvr>("IUserSvr").Login(user.UserName.Trim(), user.PassWord.Trim().ToMD5());
            }
            catch (LuKouException e)
            {
                ModelState.AddModelError("Error", e.Message);
                return View("login");
            }

            //登录失败,转到登录页面
            if (session == null)
            {
                return View("login");
            }

            //保存用户的信息到Cookie
            this.Membership.Write(new UserAuth.UserModel()
            {
                UserName = session.LoginID,
                UID = session.UserID,
            });

            this.UserSession = session;

            //如果厂商和代理还没店铺信息，转到添加店铺
            if (session.UserType != (int)EUserType.Agents && session.UserType != (int)EUserType.System)
            {
                if (session.GetShop()==null)
                {
                    return RedirectToAction("AddShop");
                }
            }

            //如里有来源地址
            if (!string.IsNullOrEmpty(referrerUrl))
            {
                return Redirect(referrerUrl);
            }
            else
            {
                return RedirectToAction("Index", "Home"); 
            }
        }
       
        public ActionResult Logout()
        {
            this.UserSession = null;
            this.Session.Clear();

            return RedirectIndex();
        }

        #endregion

        #region 注册
        
        /// <summary>
        /// 注册页面
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult Reg()
        {
            return View("reg");
        }

        /// <summary>
        /// 注册信息处理
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Reg(UserForm user)
        {
            if (!ModelState.IsValid
                || null == Session["VerifyCode"]
                  || string.Compare(user.ValidateCode, Session["VerifyCode"].ToString(), StringComparison.CurrentCultureIgnoreCase) != 0)
            {
                if (!string.IsNullOrEmpty(user.ValidateCode))
                {
                    ModelState.AddModelError("ValidateCode", "请输入正确的验证码。");
                }
                return View();
            }

            long userid = 0;
            var server = ServiceHelper.Get<IUserSvr>("IUserSvr");

            try {
                userid = server.AddUser(new User
                {
                    LoginID = user.LoginID,
                    PassWord = user.PassWord.ToMD5(),
                    Email = user.Email,
                    Mobile = user.Mobile,
                    MSN = user.MSN,
                    Name = user.Name,
                    QQ = user.QQ,
                    Sex = (int)user.UserSex,
                    ShopURL = user.ShopURL,
                    UserType = (int)user.UserType,
                    WangWang = user.WangWang,
                    VerifyState = (int)EUserVerifyState.Verified
                });
            }
            catch (LuKouException e)
            {
                this.ModelState.AddModelError("RegError", e.Message);
                return View();
            }

            if (userid <= 0)
            {
                this.ModelState.AddModelError("RegError", "用户注册失败");
                return View();
            }

            //注册成功，用户进行自动登录
            UserSession session = server.Login(user.LoginID, user.PassWord.ToMD5());
            this.Membership.Write(new UserAuth.UserModel()
            {
                UserName = session.LoginID,
                UID = session.UserID
            });
            this.UserSession = session;

            //厂家和代理转到添加店铺页面
            return RedirectToAction("AddShop");
        }

        #endregion

        #region 添加店铺信息

        [HttpGet]
        [WebAuthorize(UserType = WebUserType.Seller | WebUserType.Shipped | WebUserType.Photography)]
        public ActionResult AddShop()
        {
            User user = this.UserSession.GetUserInfo();
            ShopForm form = new ShopForm()
            {
                Phone = user.Mobile,
                QQ = user.QQ,
                WangWang = user.WangWang
            };

            return View(form);
        }

        [HttpPost]
        [WebAuthorize(UserType = WebUserType.Seller | WebUserType.Shipped | WebUserType.Photography)]
        public ActionResult AddShop(ShopForm shop)
        {
            //店铺的基础信息
            Shop shopinfo = new Shop(){
                FullName = shop.FullName,
                SummaryName = shop.SummaryName,
                SecondlevelDomain = shop.SecondlevelDomain,
                Phone = shop.Phone,
                QQ=shop.QQ,
                WangWang = shop.WangWang,
                Address = shop.Address
            };

            shopinfo.UserID = this.UserSession.UserID;
            switch (this.UserSession.UserType)
            {
                case (int)EUserType.Vendor:
                    shopinfo.ShopType = (int)EShopType.VendorShop;
                    break;
                case (int)EUserType.Photography:
                    shopinfo.ShopType = (int)EShopType.PhotographyShop;
                    break;
                case (int)EUserType.Shipped:
                    shopinfo.ShopType = (int)EShopType.ShippedShop;
                    break;
            }

            try
            {
                ShopService.Instance().AddShop(shopinfo);
                RedirectIndex();
            }
            catch (Exception e)
            {
                ModelState.AddModelError("RegError", e.Message);
            }

            return View();
        }

        #endregion
    }
}
